package com.hznu.coursemanagerbackend.modules.sys.service.impl;

import com.alibaba.druid.sql.PagerUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hznu.coursemanagerbackend.common.cryptolib.CryptoApp;
import com.hznu.coursemanagerbackend.common.utils.MapUtils;
import com.hznu.coursemanagerbackend.common.utils.PageUtils;
import com.hznu.coursemanagerbackend.common.utils.Query;
import com.hznu.coursemanagerbackend.modules.sys.bean.UserLoadBase;
import com.hznu.coursemanagerbackend.modules.sys.dao.StudentInfoDao;
import com.hznu.coursemanagerbackend.modules.sys.dao.TeacherInfoDao;
import com.hznu.coursemanagerbackend.modules.sys.entity.Course;
import com.hznu.coursemanagerbackend.modules.sys.entity.StudentInfo;
import com.hznu.coursemanagerbackend.modules.sys.entity.TeacherInfo;
import com.hznu.coursemanagerbackend.modules.sys.entity.User;
import com.hznu.coursemanagerbackend.modules.sys.dao.UserDao;
import com.hznu.coursemanagerbackend.modules.sys.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hznu.coursemanagerbackend.modules.sys.service.base.PasswordHelper;
import com.hznu.coursemanagerbackend.myBeans.ConfigParameters;
import com.hznu.coursemanagerbackend.myBeans.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.html.parser.Entity;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author DragonDoor
 * @since 2018-11-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private PasswordHelper passwordHelper;

    @Autowired
    private ConfigParameters configParameters;

    @Autowired
    private TeacherInfoService teacherInfoService;

    @Autowired
    private StudentInfoService studentInfoService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private MajorService majorService;

    @Autowired
    private ClassService classService;

    @Override
    public void add(User user)
    {
        if(user.getPassword()==null)
        {
            user.setPassword(configParameters.getDefaultPassword());
        }
        passwordHelper.encryptPassword(user); // 加密密码
        this.insert(user);
        switch (user.getUsertype())
        {
            case 1:
            {
                teacherInfoService.insert(user.getTeacherInfo());
                break;
            }
            case 2:
            {
                studentInfoService.insert(user.getStudentInfo());
                break;
            }
        }
    }

    @Override
    public User findById(Integer id)
    {
        User user = this.selectById(id);
        switch (user.getUsertype())
        {
            case 1:
            {
                TeacherInfo teacherInfo = teacherInfoService.selectOne(new EntityWrapper<TeacherInfo>().eq("userid",user.getId()));
                if(teacherInfo!=null)
                {
                    teacherInfo.setDepartment(departmentService.selectById(teacherInfo.getDepartmentid()));
                    teacherInfo.setSchool(schoolService.selectById(teacherInfo.getSchoolid()));
                    user.setTeacherInfo(teacherInfo);

                }

                break;
            }
            case 2:
            {
                StudentInfo studentInfo = studentInfoService.selectOne(new EntityWrapper<StudentInfo>().eq("userid",user.getId()));

                if(studentInfo!=null)
                {
                    studentInfo.setDepartment(departmentService.selectById(studentInfo.getDepartmentid()));
                    studentInfo.setSchool(schoolService.selectById(studentInfo.getSchoolid()));
                    studentInfo.setClazz(classService.selectById(studentInfo.getClassid()));
                    studentInfo.setMajor(majorService.selectById(studentInfo.getMajorid()));
                    user.setStudentInfo(studentInfo);
                }
                break;
            }
        }
        user.setPassword(null);
        user.setSalt(null);
        return user;
    }

    @Override
    public PageUtils queryPage(Map<String,Object> params)
    {
        String keyword = (String)params.get("keyword");
        Page<User> page = this.selectPage(
                new Query<User>(params).getPage(),
                new EntityWrapper<User>().like(keyword!=null,"username",keyword).or().
                        like(keyword!=null,"realname",keyword).or().
                        like(keyword!=null,"workid",keyword)
        );

        return new PageUtils(page);
    }

    @Override
    public void modify(User user)
    {
        this.updateById(user);
        if(user.getTeacherInfo()!=null)
        {
            teacherInfoService.update(user.getTeacherInfo(),new EntityWrapper<TeacherInfo>().eq("userid",user.getId()));
        }else if(user.getStudentInfo()!=null)
        {
            studentInfoService.update(user.getStudentInfo(),new EntityWrapper<StudentInfo>().eq("userid",user.getId()));
        }
    }

    @Override
    public Boolean validatePassword(User sessionUser, String password) {
        try {
            String oldPassword = com.hznu.coursemanagerbackend.common.utils.Utils.bytesToHexString(CryptoApp.PwdTransValue(password.getBytes(), com.hznu.coursemanagerbackend.common.utils.Utils.hexStringToBytes(sessionUser.getSalt())));
            return oldPassword.equals(sessionUser.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Integer LoadBatch(List<Object> objectList, UserLoadBase userLoadBase){
        Integer count=0;
        try{
            for (Object object : objectList){
                Map<String, Object> map= MapUtils.getKeyAndValue(object);
                User user=new User();
                user.setUsertype(userLoadBase.getUsertype());
                user.setUniversityid(userLoadBase.getUniversityid());
                user.setSchoolid(userLoadBase.getSchoolid());
                if(map.get("workId")!=null){
                    user.setWorkid((String) map.get("workId"));
                    user.setUsername((String) map.get("workId"));
                }else{
                    continue;
                }
                if(map.get("realName")!=null){
                    user.setRealname((String) map.get("realName"));
                }else{
                    continue;
                }
                if(map.get("sex")!=null){
                    user.setSex(Integer.parseInt((String)map.get("sex")));
                }else{
                    continue;
                }
                if(this.selectCount(new EntityWrapper<User>().eq("workid",user.getWorkid()))>0){
                    continue;
                }else {
                    user.setPassword(configParameters.getDefaultPassword());
                    passwordHelper.encryptPassword(user); // 加密密码
                    if(userLoadBase.getUsertype()==1){
                        this.insert(user);
                        TeacherInfo teacherInfo=new TeacherInfo();
                        teacherInfo.setUserid(user.getId());
                        teacherInfo.setDepartmentid(userLoadBase.getDepartmentid());
                        teacherInfo.setSchoolid(userLoadBase.getSchoolid());
                        teacherInfoService.insert(teacherInfo);
                        count++;
                    }else if(userLoadBase.getUsertype()==2){
                        this.insert(user);
                        StudentInfo studentInfo=new StudentInfo();
                        studentInfo.setUserid(user.getId());
                        studentInfo.setSchoolid(userLoadBase.getSchoolid());
                        studentInfo.setClassid(userLoadBase.getClassid());
                        studentInfo.setDepartmentid(userLoadBase.getDepartmentid());
                        studentInfo.setMajorid(userLoadBase.getMajorid());
                        studentInfoService.insert(studentInfo);
                        count++;
                    }else{
                       break;
                    }
                }
            }
            return count;
        }catch(Exception e){
        e.printStackTrace();
        return count;
        }
    }
}
